package com.withoutwords.ui.drawing;

import java.io.ByteArrayOutputStream;

import com.withoutwords.engine.Common;
import com.withoutwords.ui.drawing.DrawingSettingsDialog.DrawingOptionsListener;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.EmbossMaskFilter;
import android.graphics.MaskFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;

public class DefaultDrawingController extends BaseDrawingController implements
		DrawingOptionsListener {

	private Paint mPaint;
	private MaskFilter mEmboss;
	private MaskFilter mBlur;
	private DrawingView mDrawingView;
	


	DrawingSettingsDialog mDlgSettings ;
	@Override
	public void undo() {
		mDrawingView.undo();

	}

	@Override
	public void onEraseModeActiviated() {
		
		mPaint.setMaskFilter(null);
		mPaint.setColor(Color.TRANSPARENT);
		mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
		
		new EraserDialog(mContext, new EraserDialog.IEraserListener() {
			
			@Override
			public void eraserWidthChanged(int eraserWidth) {
				mPaint.setStrokeWidth(eraserWidth);
				
				//mPaint.setStrokeWidth(12);
				
			}
			
			@Override
			public void clearAll() {
				DefaultDrawingController.this.clearCurrentDrawing();
				
			}
		}).show();

	}

	@Override
	public void onSettingsRequested() {
		mPaint.setMaskFilter(mBlur);
		mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SCREEN));
		
		mDlgSettings = new DrawingSettingsDialog(mContext, this, mPaint.getColor(),mPaint.getStrokeWidth());
		mDlgSettings.show();

	}

	@Override
	public byte[] getDrawingBytesToSend() {
		if (mDrawingView != null) {
			return mDrawingView.getDrawing();
		}
		return null;
	}

	@Override
	public void setCurrentDrawing(byte[] data) {
		if (mDrawingView != null) {
			mDrawingView.setDrawing(data);
		}

	}

	@Override
	public void initializeViews(Context context, ViewGroup parent,
			boolean bViewOnly) {
		
		super.initializeViews(context, parent, bViewOnly);
		mPaint = new Paint();
		mPaint.setAntiAlias(true);
		mPaint.setDither(true);
		mPaint.setColor(0xCCFFFFFF);
		mPaint.setStyle(Paint.Style.STROKE);
		mPaint.setStrokeJoin(Paint.Join.ROUND);
		mPaint.setStrokeCap(Paint.Cap.ROUND);
		mPaint.setStrokeWidth(Common.adjustSize(8, context) );

		/*
		 * mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6,
		 * 3.5f);
		 */

		
		
		mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL);

		mPaint.setMaskFilter(mBlur);

		
		mDrawingView = new DrawingView(mContext);
		mDrawingView.setLayoutParams(new LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

		parent.addView(mDrawingView);
		bViewOnlyMode = bViewOnly;

	}

	@Override
	public void clearCurrentDrawing() {
		mDrawingView.clear();
	}

	@Override
	public void colorChanged(int color) {
		mPaint.setColor(color);
		mDlgSettings.dismiss();
	}

	public class DrawingView extends View {

		private static final float MINP = 0.25f;
		private static final float MAXP = 0.75f;

		

		// TODO : see where to recycle this bitmap
		private Bitmap mBitmap;
		private Bitmap mLastBitmap;
		private Canvas mCanvas;
		private Path mPath;
		private Paint mBitmapPaint;

		public DrawingView(Context c) {
			super(c);

			mBitmap = Bitmap.createBitmap(drawingBitmapWidth, drawingBitmapHeight,
					Bitmap.Config.ARGB_8888);
			mCanvas = new Canvas(mBitmap);
			mPath = new Path();
			mBitmapPaint = new Paint(Paint.DITHER_FLAG);

			setBackgroundColor(Color.TRANSPARENT);
		}

		@Override
		protected void onSizeChanged(int w, int h, int oldw, int oldh) {
			super.onSizeChanged(w, h, oldw, oldh);
		}

		@Override
		protected void onDraw(Canvas canvas) {
			canvas.drawColor(Color.TRANSPARENT);

			if (mBitmap != null && !mBitmap.isRecycled())
				canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);

			canvas.drawPath(mPath, mPaint);

		}

		private float mX, mY;
		private static final float TOUCH_TOLERANCE = 4;

		private void touch_start(float x, float y) {
			mPath.reset();
			mPath.moveTo(x, y);
			mX = x;
			mY = y;
		}

		private void touch_move(float x, float y) {
			float dx = Math.abs(x - mX);
			float dy = Math.abs(y - mY);
			if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
				mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
				mX = x;
				mY = y;
			}
		}

		private void touch_up() {
			if (mLastBitmap != null && !mLastBitmap.isRecycled())
				mLastBitmap.recycle();
			mLastBitmap = Bitmap.createBitmap(mBitmap);
			mPath.lineTo(mX, mY);
			// commit the path to our offscreen
			mCanvas.drawPath(mPath, mPaint);
			// kill this so we don't double draw
			mPath.reset();
		}

		@Override
		public boolean onTouchEvent(MotionEvent event) {
			if (!bViewOnlyMode) {
				float x = event.getX();
				float y = event.getY();

				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					touch_start(x, y);
					invalidate();
					break;
				case MotionEvent.ACTION_MOVE:
					touch_move(x, y);
					invalidate();
					break;
				case MotionEvent.ACTION_UP:
					touch_up();
					invalidate();
					break;
				}
			}
			return true;
		}

		public void clear() {
			if (mBitmap != null && !mBitmap.isRecycled())
				mBitmap.recycle();
			mBitmap = Bitmap.createBitmap(drawingBitmapWidth, drawingBitmapHeight,
					Bitmap.Config.ARGB_8888);
			mCanvas = new Canvas(mBitmap);
			invalidate();
		}

		public void setDrawing(byte[] drawingData) {
			if (drawingData != null) {
				if (mBitmap != null && !mBitmap.isRecycled())
					mBitmap.recycle();
				Bitmap smallBitmap = BitmapFactory.decodeByteArray(drawingData, 0,
						drawingData.length);
				mBitmap = Bitmap.createScaledBitmap(smallBitmap, drawingBitmapWidth, drawingBitmapHeight, true);
				mCanvas = new Canvas(mBitmap);
				smallBitmap.recycle();
				invalidate();
			}
		}

		public byte[] getDrawing() {
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			Bitmap smallBitmap  = Bitmap.createScaledBitmap(mBitmap, sendingBitmapWidth, sendingBitmapHeight, true);
			if (smallBitmap != null && !smallBitmap.isRecycled())
				smallBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
			smallBitmap.recycle();
			return stream.toByteArray();
		}

		public void undo() {
			if (mLastBitmap != null && !mLastBitmap.isRecycled()) {
				mBitmap.recycle();
				mBitmap = mLastBitmap;
				mLastBitmap = null;
				mCanvas = new Canvas(mBitmap);
				invalidate();
			}
		}
	}

	@Override
	public void brushSizeChanged(int newSize) {
		if(newSize < 1)
			newSize = 1;
		mPaint.setStrokeWidth(newSize);
		
	}

	@Override
	public byte[] getDrawingBytesToShare() {
		return addDrawingtoBackground(mContext, mDrawingView.mBitmap);
	}

}
